/* Copyright (c) 2012 swing-on-fire Team
 * 
 * This file is part of Swing-On-Fire (http://code.google.com/p/swing-on-fire), licensed under the terms of the MIT
 * License (MIT).
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
 * Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
package com.google.code.swingonfire.animation;

/**
 * An animation to execute other animation in sequential order, one animation after the other
 * 
 * @author ham
 */
public class AnimationSequence implements DurableAnimation
{

    /**
     * Creates the sequence of animations
     * 
     * @param animations the animations, must not be null, nor empty
     * @return the animation containing the sequence
     */
    public static Animation sequence(Animation... animations)
    {
        if ((animations == null) || (animations.length == 0))
        {
            throw new IllegalArgumentException("At least one animation expected");
        }

        if (animations.length == 1)
        {
            return animations[0];
        }

        return new AnimationSequence(animations);
    }

    private final Animation[] animations;

    private Animation animation;
    private int index;
    private double startTime;
    private double duration;

    /**
     * Creates the sequence
     * 
     * @param animations the animations
     */
    protected AnimationSequence(Animation... animations)
    {
        super();

        this.animations = animations;
    }

    /**
     * @return the animations
     */
    public Animation[] getAnimations()
    {
        return animations;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public double getDuration()
    {
        return duration;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void animationReset()
    {
        animation = null;
        index = 0;
        duration = 0;

        for (Animation animation : animations)
        {
            if (animation instanceof ResetableAnimation)
            {
                try
                {
                    ((ResetableAnimation) animation).animationReset();
                }
                catch (Exception e)
                {
                    throw new AnimationRuntimeException(animation, "Unhandled exception in animation", e);
                }
            }

            double currentDuration =
                (animation instanceof DurableAnimation) ? ((DurableAnimation) animation).getDuration() : Double.NaN;

            if ((!Double.isNaN(duration)) && (!AnimationUtil.isUndefined(currentDuration)))
            {
                duration += currentDuration;
            }
            else
            {
                duration = Double.NaN;
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public double animationStep(double delay, double time, double fraction)
    {
        if (animation == null)
        {
            animation = animations[index];
            startTime = time;
        }

        time = time - startTime;

        double duration =
            (animation instanceof DurableAnimation) ? ((DurableAnimation) animation).getDuration() : Double.NaN;

        try
        {
            delay =
                AnimationUtil.animationResult(
                    animation.animationStep(delay, time, AnimationUtil.toFraction(time, duration)), time, duration);
        }
        catch (AnimationAbortedException e)
        {
            delay = Double.NaN;
        }
        catch (Exception e)
        {
            throw new AnimationRuntimeException(animation, "Invocation of animationStep caused exception", e);
        }

        if (AnimationUtil.isFinished(delay))
        {
            animation = null;
            index += 1;

            if (index < animations.length)
            {
                delay = 0;
            }
        }

        return delay;
    }
}
